package com.atguigu.yygh.hosp.service.impl;/*
 * @author: XueYouPeng
 * @time: 2023/6/9 19:18
 */

import com.alibaba.fastjson.JSON;
import com.atguigu.exphandler.YyghException;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    DepartmentRepository departmentRepository;


    /*
     * 上传科室
     * 1、签名校验，和上传医院的校验方式一致
     * 2、判断该科室是否存在，如果存在，执行更新操作；不存在，执行新增操作
     * @author: XueYouPeng
     * @time: 2023/6/9 19:22
     */
    @Override
    public void saveDepartment(Map<String, Object> paramMap) {
        //根据hoscode+depcode 查询某个医院下的某个科室
        String hoscode = (String) paramMap.get("hoscode");
        String depcode = (String) paramMap.get("depcode");

        if (StringUtils.isEmpty(hoscode)){
            throw new YyghException(20001,"医院编号为空");
        }
        if (StringUtils.isEmpty(depcode)){
            throw new YyghException(20001,"科室编号为空");
        }

        //paramMap转成department对象
        String jsonString = JSON.toJSONString(paramMap);
        Department department = JSON.parseObject(jsonString, Department.class);

        Department departmentFromMongo= departmentRepository.findByHoscodeAndDepcode(hoscode,depcode);

        if (departmentFromMongo == null){
            //执行新增
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            departmentRepository.save(department);
        }else{
            //执行修改
            department.setCreateTime(departmentFromMongo.getCreateTime());
            department.setUpdateTime(new Date());
            //修改要有id
            department.setId(departmentFromMongo.getId());
            departmentRepository.save(department);
        }
    }


    /*
     * 条件查询+分页查询+创建时间降序排序。将分页查询的Page对象存入到data属性。
     * @author: XueYouPeng
     * @time: 2023/6/9 19:38
     */
    @Override
    public Page<Department> list(Map<String, Object> paramMap) {
        //先得到参数
        String hoscode = (String) paramMap.get("hoscode");

        //准备分页参数
        Integer pageNum = Integer.parseInt(paramMap.get("page") + "");
        Integer pageSize = Integer.parseInt(paramMap.get("limit") + "");

        //准备分页查询的条件
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department);

        //根据创建时间进行排序
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC,"creatTime"));
        Page<Department> departmentPage = departmentRepository.findAll(example, pageRequest);

        return departmentPage;
    }

    /*
     * 根据医院编号+科室编号删除
     * @author: XueYouPeng
     * @time: 2023/6/9 20:00
     */
    @Override
    public void remove(Map<String, Object> paramMap) {
        //准备删除的条件
        String hoscode = (String) paramMap.get("hoscode");
        String depcode = (String) paramMap.get("depcode");

        if (StringUtils.isEmpty(hoscode)) {
            throw new YyghException(20001,"医院编号为空");
        }
        if (StringUtils.isEmpty(depcode)){
            throw new YyghException(20001,"科室编号为空");
        }

        //查询mogoDb中是否有此数据
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            departmentRepository.deleteById(department.getId());
        }
    }

    @Override
    public List<DepartmentVo> findDeptList(String hoscode) {

        //1、查询该医院所有的小科室
        List<Department> list = departmentRepository.findByHoscode(hoscode);

        //2、遍历，获取不同的大科室编号bigcode，存放set中
        HashSet<String> set = new HashSet<>();
        list.forEach(department -> {
            String bigcode = department.getBigcode();
            set.add(bigcode);
        });

        //3、对set遍历， 每个bigcode创建一个大科室对象DepartmentVo，  根据每个bigcode查询小科室集合
        ArrayList<DepartmentVo> bigDepList = new ArrayList<>();
        set.forEach(bigCode -> {

            //根据bigcode查询小科室集合（同一个大科室下的小科室列表，这一组小科室中每个小科室的大科室编号和大科室名称都是相同的）
            List<Department> smallList = departmentRepository.findByBigcode(bigCode);

            //有多少不同的bigcode，就需要创建多少个大科室对象
            //大科室对象
            DepartmentVo bigDept = new DepartmentVo();
            //大科室编号
            bigDept.setDepcode(bigCode);
            //大科室名称
            bigDept.setDepname(smallList.get(0).getDepname());
            //当前大科室的小科室集合
            bigDept.setChildren(this.transfer(smallList));

            bigDepList.add(bigDept);
        });
        return bigDepList;
    }

    private List<DepartmentVo> transfer(List<Department> smallList) {
        ArrayList<DepartmentVo> list = new ArrayList<>();

        smallList.forEach(department -> {
            DepartmentVo small = new DepartmentVo();
            //小科室编号
            small.setDepcode(department.getDepcode());
            //小科室名称
            small.setDepname(department.getDepname());
            //小科室没有下级科室
            small.setChildren(null);

            list.add(small);
        });
        return list;
    }


}
